from flask import request
from flask_restful import Resource
from common.resp import ajax_data, ajax_page, ajax_error, ajax_success
from core import db
from datetime import datetime
import hashlib

class LogModel(db.Model):
    __tablename__ = "sys_log"

    id = db.Column(db.Integer, autoincrement=True, primary_key=True)
    user_id = db.Column(db.Integer, nullable=True)  # 标注用户
    account = db.Column(db.String(50), unique=True)
    module = db.Column(db.String(50))
    action = db.Column(db.String(50))
    log_ip = db.Column(db.String(50))
    log_time = db.Column(db.DateTime, default=datetime.now)
    status = db.Column(db.Integer, default=200)
    params = db.Column(db.String(200), default='admin')

    def to_json(self):
        return {
            'id': self.id,
            'account': self.account,
            'module': self.module,
            'action': self.action,
            'log_ip': self.log_ip,
            'log_time': self.log_time.strftime('%Y-%m-%d %H:%M:%S') if self.log_time else None,
            'status': self.status,
            'params': self.params
        }

class LogResource(Resource):
    def get(self):
        query = request.args;
        filters = []
        if query.get('module'):
            filters.append(LogModel.module.like('%' + query['module'] + '%'))
        if query.get('action'):
            filters.append(LogModel.action.like('%' + query['action'] + '%'))
        if query.get('status'):
            filters.append(LogModel.status == query['status'])
        if query.get('account'):
            filters.append(LogModel.account.like('%' + query['account'] + '%'))

        paginate = LogModel.query.filter(
            *filters).paginate(
            page=int(query.get('page', 1)), per_page=int(query.get('limit', 10)), error_out=False)

        return ajax_page([log.to_json() for log in paginate.items], paginate.total)

    def post(self):
        data = request.get_data().decode('utf-8')
        log = LogModel(
            account = data['account'],
            module = data['module'],
            action = data['action'],
            log_ip = data['log_ip'],
            status = '1',
            params = data.get('params', '{}')
        )
        db.session.add(log)
        db.session.commit()
        return ajax_success('日志创建成功')

class LogDetail(Resource):
    def get(self, id):
        if id:
            log = LogModel.query.get_or_404(id)
            return ajax_data(log.to_json())
        else:
            return ajax_error('参数错误')

    def delete(self, id):
        log = LogModel.query.get_or_404(id)
        db.session.delete(log)
        db.session.commit()
        return ajax_success('日志删除成功')
